import { CRYSTAL_CONFIG, CYSTAL, DEBUG, ENV_MAP_B } from "@/config";
import { sendMsg } from "@/utils";
import {
  Instances,
  MeshRefractionMaterial,
  useEnvironment,
  useGLTF,
} from "@react-three/drei";
import { InstancedMeshProps, ThreeEvent } from "@react-three/fiber";
import { InstancedMesh, Mesh } from "three";
import { CrystalProp } from "@/hooks/useConfig";
import { setDebug } from "@/stores/debug";
import { memo, useRef } from "react";
import Diamond from "./diamond";
import { setModel } from "@/stores/models";

let isAnime = false;
export default memo(function Diamonds({
  diamonds = [],
  config = CRYSTAL_CONFIG,
  envMap = ENV_MAP_B,
  ...props
}: DiamondProps) {
  const { nodes } = useGLTF(CYSTAL);
  const geometry = (nodes.crystalpCylinder1 as Mesh).geometry;
  const env = useEnvironment({ files: envMap });
  const ref = useRef<InstancedMesh>(null);

  // 与水晶的交互
  function onClick(e: ThreeEvent<MouseEvent>, id: number, name: string) {
    e.stopPropagation();
    if (DEBUG) {
      setDebug({ target: e.eventObject });
    } else {
      if (isAnime) return;
      isAnime = true;
      setModel({ startAnim: true });
      setTimeout(() => {
        sendMsg({
          action: "pop",
          content: { id, name },
        });
        isAnime = false;
      }, 1500);
    }
  }

  return (
    <group>
      <Instances geometry={geometry} {...props} ref={ref}>
        <MeshRefractionMaterial envMap={env} {...config} toneMapped={false} />
        {diamonds.map(({ id, ...prop }) => (
          <Diamond
            key={id}
            id={id}
            {...prop}
            speed={Math.random()}
            onClick={(e) => onClick(e, id, prop.name)}
          />
        ))}
      </Instances>
    </group>
  );
});
type DiamondProps = {
  diamonds?: CrystalProp[];
  config?: {
    bounces: number;
    aberrationStrength: number;
    ior: number;
    fresnel: number;
    color: string;
  };
  envMap?: string;
} & InstancedMeshProps;
